const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 关注用户
router.post('/users/:id/follow', (req, res) => {
  const followingId = req.params.id;
  const followerId = req.user.id;

  if (followerId === followingId) {
    return res.status(400).json({ error: '不能关注自己' });
  }

  db.query(
    'INSERT INTO follows (follower_id, following_id) VALUES (?, ?)',
    [followerId, followingId],
    (error) => {
      if (error) {
        return res.status(500).json({ error: error.message });
      }
      res.json({ message: '关注成功' });
    }
  );
});

// 取消关注
router.delete('/users/:id/follow', (req, res) => {
  const followingId = req.params.id;
  const followerId = req.user.id;

  db.query(
    'DELETE FROM follows WHERE follower_id = ? AND following_id = ?',
    [followerId, followingId],
    (error) => {
      if (error) {
        return res.status(500).json({ error: error.message });
      }
      res.json({ message: '取消关注成功' });
    }
  );
});

// 获取用户关注列表
router.get('/users/:id/following', (req, res) => {
  const userId = req.params.id;

  db.query(`
    SELECT u.id, u.username, u.avatar
    FROM follows f
    JOIN users u ON f.following_id = u.id
    WHERE f.follower_id = ?
  `, [userId], (error, results) => {
    if (error) {
      return res.status(500).json({ error: error.message });
    }
    res.json(results);
  });
});

module.exports = router; 